<template>
  <el-form
    ref="unitFormRef"
    :model="formData"
    :rules="rules"
    label-width="120px"
    class="unit-form"
  >
    <!-- 使用配置进行渲染表单分组 -->
    <template v-for="(group, groupIndex) in formConfig" :key="groupIndex">
      <div class="form-group">
        <div class="form-group-title">{{ group.title }}</div>
        <div class="form-group-content">
          <!-- 遍历每个分组中的表单项 -->
          <template
            v-for="(field, fieldIndex) in group.fields"
            :key="fieldIndex"
          >
            <el-form-item
              v-if="getFieldVisibility(field)"
              :label="field.label"
              :prop="field.prop"
            >
              <!-- 下拉选择框 -->
              <template
                v-if="
                  field.type === 'select' &&
                  field.optionsSource === 'kwaiApplication'
                "
              >
                <div class="flex items-center gap-2">
                  <el-select
                    v-model="formData[field.prop]"
                    :placeholder="field.placeholder"
                    :filterable="field.filterable || false"
                    :multiple="field.multiple || false"
                    :disabled="isReadOnly"
                    class="flex-1"
                    style="width: 300px"
                  >
                    <el-option
                      v-for="option in getFieldOptions(field)"
                      :key="option.value"
                      :label="option.key"
                      :value="option.value"
                    />
                  </el-select>
                  <el-button
                    :loading="refreshCooldown"
                    :disabled="refreshCooldown"
                    @click="refreshApplicationList"
                  >
                    {{ refreshCooldown ? `${refreshCountdown}s` : "刷新" }}
                  </el-button>
                </div>
              </template>
              <template v-else-if="field.type === 'select'">
                <el-select
                  v-model="formData[field.prop]"
                  :placeholder="field.placeholder"
                  :filterable="field.filterable || false"
                  :multiple="field.multiple || false"
                  :disabled="isReadOnly"
                >
                  <el-option
                    v-for="option in getFieldOptions(field)"
                    :key="option.value"
                    :label="option.key"
                    :value="option.value"
                  />
                </el-select>
              </template>

              <!-- 输入框 -->
              <template v-else-if="field.type === 'input'">
                <el-input
                  v-model="formData[field.prop]"
                  :placeholder="field.placeholder"
                  :maxlength="field.maxlength || 100"
                  :show-word-limit="field.showWordLimit || false"
                  :disabled="isReadOnly"
                />
              </template>

              <!-- 数字输入框 -->
              <template v-else-if="field.type === 'number'">
                <el-input-number
                  v-model="formData[field.prop]"
                  :min="field.min || 0"
                  :precision="field.precision || 0"
                  :step="field.step || 1"
                  :placeholder="field.placeholder"
                  :disabled="isReadOnly"
                />
              </template>

              <!-- 人群定向选择 -->
              <template v-else-if="field.type === 'audience'">
                <div class="audience-selector">
                  <el-button
                    type="primary"
                    :disabled="isReadOnly"
                    @click="openAudienceDialog(field.prop)"
                  >
                    {{
                      formData[field.prop]?.length
                        ? `已选择${formData[field.prop].length}个人群`
                        : field.placeholder
                    }}
                  </el-button>
                  <div
                    v-if="formData[field.prop]?.length"
                    class="selected-audience"
                  >
                    <el-tag
                      v-for="item in getSelectedAudienceDisplay(field.prop)"
                      :key="item.orientationId"
                      closable
                      :disable-transitions="false"
                      @close="removeAudience(item.orientationId, field.prop)"
                    >
                      {{ item.orientationName }}
                    </el-tag>
                  </div>
                </div>
              </template>

              <!-- 搜索下拉框 -->
              <template v-else-if="field.type === 'searchSelect'">
                <div class="flex flex-1">
                  <el-select
                    v-model="formData[field.prop]"
                    :placeholder="field.placeholder"
                    filterable
                    :disabled="isReadOnly"
                  >
                    <el-option
                      v-for="option in kwaiPixelList"
                      :key="option.pixelId"
                      :label="`${option.pixelName} (ID: ${option.pixelId})`"
                      :value="option.pixelId"
                    />
                  </el-select>
                  <el-button
                    v-if="field.prop == 'pixelId'"
                    :loading="pixelRefreshCooldown"
                    :disabled="pixelRefreshCooldown"
                    @click="refreshKwaiPixelList"
                  >
                    {{
                      pixelRefreshCooldown
                        ? `${pixelRefreshCountdown}s`
                        : "刷新"
                    }}
                  </el-button>
                </div>
              </template>

              <!-- 单选按钮组 -->
              <template v-else-if="field.type === 'radio'">
                <el-radio-group
                  v-model="formData[field.prop]"
                  :disabled="isReadOnly"
                >
                  <el-radio
                    v-for="option in field.options"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </template>

              <template v-else-if="field.type === 'devicePriceInfo'">
                <el-radio-group
                  v-model="customeDevicePrice"
                  :disabled="isReadOnly"
                >
                  <el-radio :label="0">不限</el-radio>
                  <el-radio :label="1">自定义</el-radio>
                </el-radio-group>
                <div
                  v-if="customeDevicePrice == 1"
                  class="price-range-selector"
                >
                  <el-select
                    v-model="formData[field.prop][0]"
                    style="width: 100px"
                    placeholder="最低价格"
                    :disabled="isReadOnly"
                    @change="handleMinPriceChange"
                  >
                    <el-option
                      v-for="option in getFieldOptions(field)"
                      :key="option.value"
                      :label="option.key"
                      :value="option.value"
                    />
                  </el-select>
                  <span class="price-range-separator">至</span>
                  <el-select
                    v-model="formData[field.prop][1]"
                    style="width: 100px"
                    placeholder="最高价格"
                    :disabled="isReadOnly || !formData[field.prop][0]"
                  >
                    <el-option
                      v-for="option in getMaxPriceOptions(field)"
                      :key="option.value"
                      :label="option.key"
                      :value="option.value"
                    />
                  </el-select>
                  <span class="price-range-separator">USD</span>
                </div>
              </template>

              <!-- 排期控件 -->
              <template v-else-if="field.type === 'schedule'">
                <div class="schedule-selector">
                  <el-radio-group
                    v-model="formData.scheduleType"
                    :disabled="isReadOnly"
                  >
                    <el-radio label="forever">今日起持续投放</el-radio>
                    <el-radio label="custom">自定义</el-radio>
                  </el-radio-group>

                  <div
                    v-if="formData.scheduleType === 'custom'"
                    class="custom-schedule"
                  >
                    <div class="time-range">
                      <span class="time-label">开始时间：</span>
                      <el-date-picker
                        v-model="formData.startTime"
                        type="date"
                        :disabled="isReadOnly"
                        placeholder="选择开始时间"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledStartDate"
                        :disabled-hours="disabledStartHours"
                        :disabled-minutes="disabledStartMinutes"
                      />
                    </div>
                    <div class="time-range">
                      <span class="time-label">结束时间：</span>
                      <el-date-picker
                        v-model="formData.endTime"
                        type="date"
                        :disabled="isReadOnly"
                        placeholder="选择结束时间"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledEndDate"
                      />
                    </div>
                  </div>
                </div>
              </template>

              <!-- 投放时段控件 -->
              <template v-else-if="field.type === 'timeSchedule'">
                <div class="time-schedule-selector">
                  <el-radio-group
                    v-model="formData.timeScheduleType"
                    :disabled="isReadOnly"
                  >
                    <el-radio label="allDay">全天</el-radio>
                    <el-radio label="custom">特定时间</el-radio>
                  </el-radio-group>

                  <div
                    v-if="formData.timeScheduleType === 'custom'"
                    class="custom-time-schedule"
                  >
                    <el-button type="primary" @click="openTimeScheduleDialog">
                      {{ getSelectedTimeScheduleText() }}
                    </el-button>
                    <el-button
                      v-if="showClearTimeSchedule"
                      @click="formData.timeSchedule = {}"
                    >
                      清除全部
                    </el-button>
                    <div class="mt-2">
                      <div class="slots-container">
                        <div
                          v-for="(hours, day) in formData.timeSchedule"
                          :key="day"
                        >
                          <div
                            v-if="hours.length"
                            class="flex items-center gap-4"
                          >
                            <span class="day-label">{{
                              weekDayNames[day]
                            }}</span>
                            <div class="flex flex-wrap gap-2">
                              <el-tag
                                v-for="hour in hours"
                                :key="hour"
                                type="info"
                                closable
                                @close="toggleTimeSelection(day, hour)"
                              >
                                {{ formatHour(hour) }}
                              </el-tag>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>

              <template v-else-if="field.type === 'budgetSchedule'">
                <div class="time-schedule-selector">
                  <el-table border :data="[{}]" style="width: 100%">
                    <el-table-column
                      v-for="day in 7"
                      :key="day"
                      :label="weekDayNames[day]"
                      width="150"
                    >
                      <template #default>
                        <el-input
                          v-model.number="formData.budgetSchedule[day - 1]"
                          type="number"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-form-item>
          </template>
        </div>
      </div>
    </template>
  </el-form>

  <!-- 人群定向选择弹窗 -->
  <el-dialog v-model="audienceDialogVisible" title="选择定向人群" width="800px">
    <div class="audience-filter">
      <el-input
        v-model="audienceFilter"
        placeholder="请输入人群ID或名称"
        clearable
        @input="handleAudienceFilterChange"
      >
        <template #append>
          <el-button @click="searchAudience"> 搜索 </el-button>
        </template>
      </el-input>
    </div>

    <el-table
      v-loading="audienceLoading"
      :data="audienceList"
      style="width: 100%"
      @selection-change="handleAudienceSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orientationId" label="ID" width="120" />
      <el-table-column prop="orientationName" label="人群名称" />
      <el-table-column prop="coverNum" label="人群数量" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
    </el-table>

    <el-pagination
      v-model:current-page="audiencePagination.current"
      v-model:page-size="audiencePagination.size"
      :total="audiencePagination.total"
      layout="total, prev, pager, next"
      background
      @current-change="handleAudiencePageChange"
    />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="audienceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAudienceSelection"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!-- 投放时段选择弹窗 -->
  <el-dialog
    v-model="timeScheduleDialogVisible"
    title="选择投放时段"
    width="900px"
  >
    <div class="time-schedule-grid">
      <table class="time-schedule-table">
        <thead>
          <tr>
            <th>星期/时段</th>
            <th colspan="12">上午 (00:00~11:59)</th>
            <th colspan="12">下午 (12:00~23:59)</th>
          </tr>
          <tr>
            <th />
            <th v-for="hour in 24" :key="hour - 1">{{ hour - 1 }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="day in 7" :key="day">
            <td>{{ weekDayNames[day] }}</td>
            <td
              v-for="hour in 24"
              :key="`${day}-${hour - 1}`"
              :class="{
                'time-cell': true,
                selected: isTimeSelected(day, hour - 1)
              }"
              @click="toggleTimeSelection(day, hour - 1)"
            />
          </tr>
        </tbody>
      </table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="timeScheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTimeSchedule">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  watch,
  defineEmits,
  defineProps,
  defineExpose,
  onMounted
} from "vue";
import { useUnitSelect } from "../utils/hooks";
import {
  getKwaiApplicationList,
  getKwaiPixelList,
  getMaterialVideoList,
  getKwaiAudienceList,
  getAdAccounts
} from "@/api/promotion";
import { ElMessage } from "element-plus";

// 获取广告组选项
const { unitOptions, loadUnitOptions } = useUnitSelect();

// 定义组件属性
const props = defineProps({
  // 表单数据
  modelValue: {
    type: Object,
    required: true
  },
  // 是否为只读模式
  isReadOnly: {
    type: Boolean,
    default: false
  },
  // 预设值，用于编辑或查看模式
  presetData: {
    type: Object,
    default: () => ({})
  },
  // 广告计划
  selectedCampaign: {
    type: Object,
    default: () => ({})
  }
});

// 定义事件
const emit = defineEmits(["update:modelValue", "submit", "validate"]);

// 表单引用
const unitFormRef = ref();
const customeDevicePrice = ref(0);

// 监听 customeDevicePrice 变化，初始化设备价格列表
watch(customeDevicePrice, newVal => {
  if (newVal === 0) {
    // 不限模式，清空价格列表
    formData.value.devicePriceInfoList = [];
  } else if (
    newVal === 1 &&
    (!formData.value.devicePriceInfoList ||
      !Array.isArray(formData.value.devicePriceInfoList))
  ) {
    // 自定义模式，初始化为数组
    formData.value.devicePriceInfoList = [];
  }
});
// 本地表单数据
const formData = ref({
  appId: "", // 应用ID
  unitName: "", // 广告组名称
  budgetType: "", // 预算类型
  dayBudget: 50, // 每日预算
  gender: "", // 性别
  ageList: [], // 年龄段
  countryRegionInfoList: [], // 国家地区 - 确保初始化为数组
  languageList: [], // 语言
  deviceBrandCodeList: [], // 设备品牌
  devicePriceInfoList: [], // 设备价格
  osTypeAndVersionList: [], // 操作系统
  contentInterestCodeList: [], // 兴趣分类
  placements: [], // 广告位
  linkType: "", // 链接类型
  ocpxActionType: "", // 转化目标
  // ocpxActionTypeLimit: "", // 转化目标限制
  populationIdList: [], // 人群定向ID列表
  excludePopulationIdList: [], // 人群排除ID列表
  pixelId: "", // Kwai Pixel ID
  websiteUrl: "", // 网站链接
  bid: 0, // 目标转化成本
  bidType: 10, // 计费方式，默认OCPM
  scheduleType: "forever", // 排期类型: forever-持续投放, custom-自定义
  startTime: "", // 开始时间
  endTime: "", // 结束时间
  timeScheduleType: "allDay", // 投放时段类型: allDay-全天, custom-特定时间
  timeSchedule: {}, // 投放时段, 格式: { 1: [15, 16], 2: [9, 10, 11] } 表示周一15-16点，周二9-11点
  budgetSchedule: [50, 50, 50, 50, 50, 50, 50] //周一到周六
});

// 表单验证规则
const rules = ref({
  unitName: [
    { required: true, message: "请输入广告组名称", trigger: "blur" },
    { max: 100, message: "超出可输入最长名称", trigger: "blur" }
  ],
  budgetType: [
    { required: true, message: "请选择预算类型", trigger: "change" }
  ],
  dayBudget: [{ required: true, message: "请输入每日预算", trigger: "blur" }],
  gender: [{ required: false, message: "请选择性别", trigger: "change" }],
  ageList: [{ required: false, message: "请选择年龄段", trigger: "change" }],
  countryRegionInfoList: [
    { required: true, message: "请选择国家地区", trigger: "change" }
  ],
  languageList: [{ required: false, message: "请选择语言", trigger: "change" }],
  deviceBrandCodeList: [
    { required: false, message: "请选择设备品牌", trigger: "change" }
  ],
  devicePriceInfoList: [
    {
      required: false,
      trigger: "change",
      validator: (rule, value, callback) => {
        if (customeDevicePrice.value === 0) {
          // 不限模式，不需要验证
          callback();
        } else if (!value || !Array.isArray(value)) {
          // 自定义模式下，必须是数组
          callback(new Error("请选择价格范围"));
        } else if (!value[0]) {
          callback(new Error("请选择最低价格"));
        } else if (!value[1]) {
          callback(new Error("请选择最高价格"));
        } else if (Number(value[0]) >= Number(value[1])) {
          callback(new Error("最高价格必须大于最低价格"));
        } else {
          callback();
        }
      }
    }
  ],
  osTypeAndVersionList: [
    { required: false, message: "请选择操作系统", trigger: "change" }
  ],
  contentInterestCodeList: [
    { required: false, message: "请选择内容兴趣", trigger: "change" }
  ],
  placements: [{ required: true, message: "请选择广告位", trigger: "change" }],
  linkType: [{ required: true, message: "请选择链接类型", trigger: "change" }],
  ocpxActionType: [
    { required: true, message: "请选择转化目标", trigger: "change" }
  ],
  populationIdList: [
    { required: false, message: "请选择定向人群", trigger: "change" }
  ],
  excludePopulationIdList: [
    { required: false, message: "请选择排除人群", trigger: "change" }
  ],
  pixelId: [{ required: true, message: "请选择Kwai Pixel", trigger: "change" }],
  websiteUrl: [{ required: true, message: "请输入网站链接", trigger: "blur" }],
  bid: [{ required: true, message: "请输入目标转化成本", trigger: "blur" }],
  bidType: [{ required: true, message: "请选择计费方式", trigger: "change" }],
  scheduleType: [
    { required: true, message: "请选择排期类型", trigger: "change" }
  ],
  startTime: [
    {
      required: true,
      message: "请选择开始时间",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (formData.value.scheduleType === "custom" && !value) {
          callback(new Error("请选择开始时间"));
        } else {
          callback();
        }
      }
    }
  ],
  endTime: [
    {
      required: true,
      message: "请选择结束时间",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (formData.value.scheduleType === "custom" && !value) {
          callback(new Error("请选择结束时间"));
        } else if (
          formData.value.scheduleType === "custom" &&
          formData.value.startTime &&
          value &&
          new Date(value) <= new Date(formData.value.startTime)
        ) {
          callback(new Error("结束时间必须晚于开始时间"));
        } else {
          callback();
        }
      }
    }
  ],
  timeScheduleType: [
    { required: true, message: "请选择投放时段类型", trigger: "change" }
  ],
  timeSchedule: [
    {
      validator: (rule, value, callback) => {
        if (
          formData.value.timeScheduleType === "custom" &&
          Object.keys(value).length === 0
        ) {
          callback(new Error("请选择至少一个投放时段"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});

// 表单配置
const formConfig = computed(() => [
  {
    title: "网站推广/应用推广",
    fields: [
      {
        type: "select",
        label: "链接类型",
        prop: "linkType",
        placeholder: "请选择链接类型",
        optionsSource: "linkType",
        visible: () => false,
        disabled: true
      },
      {
        type: "select",
        label: "应用",
        prop: "appId",
        placeholder: "请选择应用",
        optionsSource: "kwaiApplication",
        visible: () => props.selectedCampaign?.marketingType === 1,
        filterable: true,
        options: computed(() =>
          applicationList.value.map(app => ({
            key: `${app.appName} (ID: ${String(app.appId)})`,
            value: app.appId,
            label: `${app.appName} (ID: ${String(app.appId)})`
          }))
        )
      },
      {
        type: "input",
        label: "网站链接",
        prop: "websiteUrl",
        placeholder: "请输入网站链接",
        visible: () => props.selectedCampaign?.marketingType === 2
      },
      {
        type: "searchSelect",
        label: "Kwai Pixel",
        prop: "pixelId",
        placeholder: "请选择 Kwai Pixel",
        optionsSource: "kwaiPixel",
        visible: () => props.selectedCampaign?.marketingType === 2
      }
    ]
  },
  // 基本信息分组
  {
    title: "基本信息",
    fields: [
      {
        type: "input",
        label: "广告组名称",
        prop: "unitName",
        placeholder: "请输入广告组名称",
        maxlength: 100,
        showWordLimit: true
      }
    ]
  },
  // 定向设置分组
  {
    title: "目标人群",
    fields: [
      {
        type: "select",
        label: "目标国家",
        prop: "countryRegionInfoList",
        placeholder: "请选择目标国家",
        optionsSource: "countryRegionInfoList",
        multiple: true
      },
      {
        type: "audience",
        label: "人群定向",
        prop: "populationIdList",
        placeholder: "请选择定向人群"
      },
      {
        type: "audience",
        label: "人群排除",
        prop: "excludePopulationIdList",
        placeholder: "请选择人群排除"
      },
      {
        type: "select",
        label: "年龄",
        prop: "ageList",
        placeholder: "请选择年龄",
        optionsSource: "ageList",
        multiple: true
      },
      {
        type: "select",
        label: "性别",
        prop: "gender",
        placeholder: "请选择性别",
        optionsSource: "gender"
      },
      {
        type: "select",
        label: "语言",
        prop: "languageList",
        placeholder: "请选择语言",
        optionsSource: "languageList"
      },
      // {
      //   type: "select",
      //   label: "目标优化",
      //   prop: "ocpxActionType",
      //   placeholder: "目标优化",
      //   optionsSource: "ocpxActionType"
      // },
      {
        type: "devicePriceInfo",
        label: "设备价格",
        prop: "devicePriceInfoList",
        placeholder: "请选择设备价格",
        optionsSource: "devicePriceInfoList",
        multiple: true
      },
      {
        type: "select",
        label: "操作系统",
        prop: "osTypeAndVersionList",
        placeholder: "请选择操作系统",
        optionsSource: "osTypeAndVersionList"
      },
      {
        type: "select",
        label: "手机品牌",
        prop: "deviceBrandCodeList",
        placeholder: "请选择手机品牌",
        optionsSource: "deviceBrandCodeList",
        multiple: true
      },
      {
        type: "select",
        label: "内容兴趣",
        prop: "contentInterestCodeList",
        placeholder: "请选择内容兴趣",
        optionsSource: "contentInterestCodeList",
        multiple: true
      }
    ]
  },
  {
    title: "预算和排期",
    fields: [
      {
        type: "select",
        label: "预算类型",
        prop: "budgetType",
        placeholder: "请选择预算类型",
        optionsSource: "budgetType"
      },
      {
        type: "budgetSchedule",
        label: "预算计划",
        visible: form => form.budgetType == "3",
        prop: "budgetSchedule"
      },
      {
        type: "number",
        label: "每日预算(USD)",
        prop: "dayBudget",
        visible: form => form.budgetType == "2",
        min: 50,
        precision: 2,
        step: 0.01,
        placeholder: "请输入每日预算"
      },
      {
        type: "schedule",
        label: "排期(北京时间)",
        prop: "scheduleType"
      },
      {
        type: "timeSchedule",
        label: "投放时段(北京时间)",
        prop: "timeScheduleType"
      }
    ]
  },
  {
    title: "优化目标和计费",
    fields: [
      {
        type: "select",
        label: "优化目标",
        prop: "ocpxActionType",
        placeholder: "请选择优化目标",
        optionsSource: "ocpxActionType"
      },
      {
        type: "radio",
        label: "计费方式",
        prop: "bidType",
        options: [{ label: "OCPM(按曝光计费)", value: 10 }]
      },
      // {
      //   type: "select",
      //   label: "优化目标限制",
      //   prop: "ocpxActionTypeLimit",
      //   placeholder: "请选择优化目标限制",
      //   optionsSource: "ocpxActionTypeLimit"
      // },
      {
        type: "number",
        label: "目标转化成本",
        prop: "bid",
        placeholder: "请输入目标转化成本",
        min: 0,
        precision: 2,
        step: 0.01
      },
      {
        type: "select",
        label: "投放位置",
        prop: "placements",
        placeholder: "请选择投放位置",
        optionsSource: "placements",
        multiple: true
      }
    ]
  }
]);

// 获取字段显示状态
const getFieldVisibility = field => {
  if (field.visible) {
    return field.visible(formData.value);
  }
  return true;
};

// 获取字段选项
const getFieldOptions = field => {
  const source = field.optionsSource;
  if (source === "kwaiApplication") {
    console.log("应用列表数据:", applicationList.value);
    return applicationList.value.map(app => ({
      key: `${app.appName} (ID: ${String(app.appId)})`,
      value: app.appId,
      label: `${app.appName} (ID: ${String(app.appId)})`
    }));
  }
  if (source === "kwaiPixel") {
    return kwaiPixelList.value.map(pixel => ({
      key: `${pixel.pixelName} (ID: ${pixel.pixelId})`,
      value: pixel.pixelId
    }));
  }
  if (source === "countryRegionInfoList") {
    console.log("国家选项列表:", unitOptions.value[source]);
    // 直接返回正确格式化的选项
    if (unitOptions.value[source] && Array.isArray(unitOptions.value[source])) {
      return unitOptions.value[source].map(option => ({
        ...option,
        // 确保 value 属性是 code 值，而不是整个对象
        value: option.value || option.code || option.key
      }));
    }
  }
  return unitOptions.value[source] || [];
};

// 获取最高价格选项（过滤掉小于最低价格的选项）
const getMaxPriceOptions = field => {
  const options = getFieldOptions(field);
  const minPrice = formData.value[field.prop][0];

  if (!minPrice) return options;

  return options.filter(option => Number(option.value) > Number(minPrice));
};

// 处理最低价格变化
const handleMinPriceChange = () => {
  const devicePriceInfoList = formData.value.devicePriceInfoList;

  // 如果最高价格小于等于最低价格，则清空最高价格
  if (
    devicePriceInfoList[1] &&
    devicePriceInfoList[0] >= devicePriceInfoList[1]
  ) {
    devicePriceInfoList[1] = undefined;
  }
};

// 格式化表单数据
const formatFormData = () => {
  // 深拷贝表单数据，避免直接修改原始数据
  const data = JSON.parse(JSON.stringify(formData.value));

  // 确保必填字段存在且类型正确
  const requiredFields = {
    appId: formData.value.unitName || "", // 应用ID
    linkType: 2, // 链接类型：2-落地页
    gender: 3, // 性别：3-不限
    budgetType: 1, // 预算类型：1-不限
    ocpxActionType: null, // 转化目标：100-激活
    adCategory: 1, // 广告分类：1-效果广告
    bidType: 10, // 计费方式：10-OCPM
    unitName: formData.value.unitName || `广告组-${new Date().getTime()}` // 如果没有名称，生成一个默认名称
  };

  // 将必填字段合并到数据中，确保有值的保留，没值的使用默认值
  Object.entries(requiredFields).forEach(([key, defaultValue]) => {
    if (!data[key]) {
      data[key] = defaultValue;
    }
  });

  // 确保数值字段类型正确
  const numberFields = [
    "linkType",
    "gender",
    "budgetType",
    "ocpxActionType",
    "adCategory",
    "pixelId",
    "bidType"
  ];

  numberFields.forEach(field => {
    if (data[field] !== undefined && data[field] !== null) {
      data[field] = Number(data[field]);
    }
  });

  // 特殊处理出价（bid）- 转换为百万分之一，保证数据精度
  if (data.bid !== undefined && data.bid !== null && data.bid !== "") {
    data.bid = Math.round(Number(data.bid) * 1000000);
  }

  // 处理预算相关
  // if (data.budgetType === 2 && data.dayBudget) {
  // 转换为API需要的单位(×10^6)
  data.dayBudget = Math.round(Number(data.dayBudget) * 1000000);
  // }

  data.budgetSchedule = data.budgetSchedule.map(item => {
    if (item) {
      return Math.round(Number(item) * 1000000);
    } else {
      return item;
      // Math.round(Number(1) * 1000000);
    }
  });
  // 处理数字数组字段
  const numberArrayFields = [
    "placements",
    "ageList",
    "populationIdList",
    "excludePopulationIdList",
    "languageList",
    "deviceBrandCodeList",
    "osTypeAndVersionList",
    "contentInterestCodeList",
    "devicePriceInfoList"
  ];

  numberArrayFields.forEach(field => {
    if (!data[field]) {
      data[field] = [];
    } else if (!Array.isArray(data[field])) {
      data[field] = [data[field]];
    }

    // 确保数组中所有元素为数字类型
    data[field] = data[field].map(item => Number(item));
  });

  // 特殊处理 countryRegionInfoList
  console.log("原始 countryRegionInfoList 数据:", data.countryRegionInfoList);
  console.log(
    "原始 countryRegionInfoList 类型:",
    typeof data.countryRegionInfoList
  );

  // 判断 countryRegionInfoList 是否为数组
  if (!Array.isArray(data.countryRegionInfoList)) {
    // 如果不是数组而是单个值，将其转为数组
    const code = Number(data.countryRegionInfoList) || 1;
    data.countryRegionInfoList = [{ code: code }];
  } else if (data.countryRegionInfoList.length === 0) {
    // 如果是空数组，设置默认值
    data.countryRegionInfoList = [{ code: 1 }];
  } else {
    // 如果是数组，确保每项格式正确
    data.countryRegionInfoList = data.countryRegionInfoList.map(item => {
      if (typeof item === "object" && item !== null && item.code) {
        return { code: Number(item.code) };
      }
      return { code: Number(item) };
    });
  }

  console.log("处理后的 countryRegionInfoList:", data.countryRegionInfoList);

  // 处理投放时段
  if (data.timeScheduleType === "allDay") {
    // 全天投放时设置为空数组
    data.timeSchedule = [];
  } else if (data.timeScheduleType === "custom" && data.timeSchedule) {
    // 转换为API需要的格式
    const formattedSchedule = [];
    Object.entries(data.timeSchedule).forEach(([day, hours]) => {
      if (Array.isArray(hours) && hours.length > 0) {
        hours.forEach(hour => {
          formattedSchedule.push([Number(day), Number(hour)]);
        });
      }
    });
    data.timeSchedule = formattedSchedule;
  }

  // 移除创建API不需要的临时字段
  delete data.scheduleType;
  delete data.timeScheduleType;

  // 处理日期
  if (data.startTime) {
    if (typeof data.startTime === "string" && data.startTime.trim() === "") {
      data.startTime = undefined;
    } else {
      data.startTime = new Date(data.startTime).getTime();
    }
  }

  if (data.endTime) {
    if (typeof data.endTime === "string" && data.endTime.trim() === "") {
      data.endTime = undefined;
    } else {
      data.endTime = new Date(data.endTime).getTime();
    }
  }

  // 移除所有undefined、null和空字符串的字段
  Object.keys(data).forEach(key => {
    if (data[key] === undefined || data[key] === null || data[key] === "") {
      delete data[key];
    }
  });

  console.log("格式化后的广告组数据:", JSON.stringify(data, null, 2));
  return data;
};

// 表单验证
const validate = () => {
  return new Promise((resolve, reject) => {
    unitFormRef.value.validate((valid, fields) => {
      if (valid) {
        const formattedData = formatFormData();
        resolve(formattedData);
      } else {
        reject(fields);
      }
    });
  });
};

// 重置表单
const resetForm = () => {
  unitFormRef.value.resetFields();
};

// 监听props.modelValue变化，同步到本地formData
watch(
  () => props.modelValue,
  newVal => {
    Object.assign(formData.value, newVal);
  },
  { deep: true, immediate: true }
);

// 监听本地formData变化，同步到父组件
watch(
  formData,
  newVal => {
    emit("update:modelValue", newVal);
  },
  { deep: true }
);

// 如果有预设数据，则使用预设数据
watch(
  () => props.presetData,
  newVal => {
    if (newVal && Object.keys(newVal).length > 0) {
      Object.assign(formData.value, newVal);
      formData.value.devicePriceInfoList.length > 0
        ? (customeDevicePrice.value = 1)
        : (customeDevicePrice.value = 0);
    }
  },
  { immediate: true, deep: true }
);

// 监听 selectedCampaign 变化，自动设置 linkType
watch(
  () => props.selectedCampaign,
  newVal => {
    if (newVal) {
      // 根据 marketingType 自动设置 linkType
      if (newVal.marketingType === 1) {
        formData.value.linkType = 1; // app
      } else if (newVal.marketingType === 2) {
        formData.value.linkType = 2; // 落地页
      }
    }
  },
  { immediate: true }
);

// 对外暴露方法
defineExpose({
  validate,
  resetForm,
  formData,
  formatFormData
});

const applicationList = ref([]);
const kwaiPixelList = ref([]);

// 添加刷新按钮的冷却状态
const refreshCooldown = ref(false);
const refreshCountdown = ref(0);

// 刷新应用列表
const refreshApplicationList = async () => {
  if (refreshCooldown.value) return;

  try {
    refreshCooldown.value = true;
    refreshCountdown.value = 60;

    // 开始倒计时
    const timer = setInterval(() => {
      refreshCountdown.value--;
      if (refreshCountdown.value <= 0) {
        clearInterval(timer);
        refreshCooldown.value = false;
      }
    }, 1000);

    // 重新获取应用列表
    await loadApplicationList();
  } catch (error) {
    console.error("刷新应用列表失败:", error);
    ElMessage.error("刷新失败");
  }
};

const loadApplicationList = async () => {
  try {
    // 获取广告账户ID，优先使用选中的广告计划的账户ID
    const adAccountId =
      props.selectedCampaign?.adAccountId ||
      props.presetData?.adAccountId ||
      (adAccounts.value?.length > 0 ? adAccounts.value[0].adAccountId : null);

    if (!adAccountId) {
      console.error("未找到可用的广告账户ID");
      ElMessage.warning("未找到可用的广告账户ID");
      return;
    }

    const res = await getKwaiApplicationList({
      size: -1,
      adAccountId: adAccountId
    });
    console.log("应用列表接口返回数据:", res);
    if (res && res.list) {
      applicationList.value = res.list;
      console.log("设置后的应用列表数据:", applicationList.value);
    }
  } catch (error) {
    console.error("获取应用列表失败:", error);
    ElMessage.error("获取应用列表失败");
  }
};

const loadKwaiPixelList = async () => {
  try {
    // 获取广告账户ID，优先使用选中的广告计划的账户ID
    const adAccountId =
      props.selectedCampaign?.adAccountId ||
      props.presetData?.adAccountId ||
      (adAccounts.value?.length > 0 ? adAccounts.value[0].adAccountId : null);

    if (!adAccountId) {
      console.error("未找到可用的广告账户ID");
      ElMessage.warning("未找到可用的广告账户ID");
      return;
    }

    const res = await getKwaiPixelList({
      size: -1,
      adAccountId: adAccountId
    });
    if (res && res.list) {
      kwaiPixelList.value = res.list;
    }
  } catch (error) {
    console.error("获取Kwai Pixel列表失败:", error);
    ElMessage.error("获取Kwai Pixel列表失败");
  }
};

// 人群定向相关状态和方法
const audienceDialogVisible = ref(false);
const audienceList = ref([]);
const audienceLoading = ref(false);
const audienceFilter = ref("");
const audiencePagination = ref({
  current: 1,
  size: 10,
  total: 0
});
const tempSelectedAudience = ref([]);
const audienceInfoMap = ref(new Map());
// 当前操作的属性名（区分人群定向和人群排除）
const currentAudienceProp = ref("");

// 打开人群选择弹窗 - 统一方法，可处理不同种类的人群选择
const openAudienceDialog = (propName = "populationIdList") => {
  audienceDialogVisible.value = true;
  currentAudienceProp.value = propName;
  tempSelectedAudience.value = [...(formData.value[propName] || [])];
  // 重置分页和筛选
  audiencePagination.value.current = 1;
  audienceFilter.value = "";
  loadAudienceList();
};

// 加载人群列表
const loadAudienceList = async () => {
  audienceLoading.value = true;
  try {
    // 获取广告账户ID，优先使用选中的广告计划的账户ID
    const adAccountId =
      props.selectedCampaign?.adAccountId ||
      props.presetData?.adAccountId ||
      (adAccounts.value?.length > 0 ? adAccounts.value[0].adAccountId : null);

    if (!adAccountId) {
      console.error("未找到可用的广告账户ID");
      ElMessage.warning("未找到可用的广告账户ID");
      audienceLoading.value = false;
      return;
    }

    // 根据getKwaiAudienceList的实际参数要求调整
    const params: {
      adAccountId: number;
      page: number;
      size: number;
      dataList: any[];
      orientationName?: string;
    } = {
      adAccountId: adAccountId, // 确保为数字类型
      page: audiencePagination.value.current,
      size: audiencePagination.value.size,
      dataList: [] // API可能需要的参数，即使为空也提供
    };

    if (audienceFilter.value) {
      params.orientationName = audienceFilter.value; // 使用orientationName作为过滤参数
    }

    const res = await getKwaiAudienceList(params);
    if (res && res.list) {
      audienceList.value = res.list;
      audiencePagination.value.total = res.total || res.list.length;

      // 更新人群信息映射
      res.list.forEach(item => {
        if (item.orientationId) {
          audienceInfoMap.value.set(item.orientationId, item);
        }
      });
    } else {
      audienceList.value = [];
      audiencePagination.value.total = 0;
      console.warn("获取人群列表返回数据格式不符合预期", res);
    }
  } catch (error) {
    console.error("获取人群列表失败:", error);
    ElMessage.error("获取人群列表失败");
    audienceList.value = [];
  } finally {
    audienceLoading.value = false;
  }
};

// 处理人群筛选变化
const handleAudienceFilterChange = () => {
  audiencePagination.value.current = 1;
};

// 搜索人群
const searchAudience = () => {
  loadAudienceList();
};

// 处理分页变化
const handleAudiencePageChange = page => {
  audiencePagination.value.current = page;
  loadAudienceList();
};

// 处理表格选择变化
const handleAudienceSelectionChange = selection => {
  tempSelectedAudience.value = selection.map(item => item.orientationId);
};

// 确认人群选择 - 根据当前操作的属性名更新对应数据
const confirmAudienceSelection = () => {
  formData.value[currentAudienceProp.value] = [...tempSelectedAudience.value];
  audienceDialogVisible.value = false;
};

// 移除已选择的人群 - 根据当前操作的属性名移除对应数据
const removeAudience = (id, propName = "populationIdList") => {
  formData.value[propName] = formData.value[propName].filter(
    item => item !== id
  );
};

// 已选择的人群展示信息 - 通用方法，可获取不同种类的人群信息
const getSelectedAudienceDisplay = propName => {
  return (
    formData.value[propName]?.map(id => {
      return (
        audienceInfoMap.value.get(id) || {
          orientationId: id,
          orientationName: `ID: ${id}`
        }
      );
    }) || []
  );
};

// 计算属性：定向人群展示信息
const selectedAudienceDisplay = computed(() => {
  return getSelectedAudienceDisplay("populationIdList");
});

// 计算属性：排除人群展示信息
const excludedAudienceDisplay = computed(() => {
  return getSelectedAudienceDisplay("excludePopulationIdList");
});

// 加载广告账号列表
const adAccounts = ref<{ adAccountId: number; adAccountName: string }[]>([]);

const loadAdAccounts = async () => {
  try {
    const data = await getAdAccounts();
    adAccounts.value = data || [];
  } catch (error) {
    console.error("获取广告账号列表失败:", error);
  }
};

// 组件挂载时加载选项数据
onMounted(() => {
  formData.value.devicePriceInfoList.length > 0
    ? (customeDevicePrice.value = 1)
    : (customeDevicePrice.value = 0);
  const fn = async () => {
    loadUnitOptions();
    loadAdAccounts();
    loadApplicationList();
    loadKwaiPixelList();
  };
  fn();
});

// 投放时段相关状态和方法
const timeScheduleDialogVisible = ref(false);
const tempTimeSchedule = ref({});
const weekDayNames = {
  1: "星期一",
  2: "星期二",
  3: "星期三",
  4: "星期四",
  5: "星期五",
  6: "星期六",
  7: "星期日"
};

// 打开投放时段选择弹窗
const openTimeScheduleDialog = () => {
  timeScheduleDialogVisible.value = true;
  tempTimeSchedule.value = { ...formData.value.timeSchedule };
};

// 检查指定时段是否被选中
const isTimeSelected = (day, hour) => {
  if (!tempTimeSchedule.value[day]) return false;
  return tempTimeSchedule.value[day].includes(hour);
};

// 切换时段选择状态
const toggleTimeSelection = (day, hour) => {
  if (!tempTimeSchedule.value[day]) {
    tempTimeSchedule.value[day] = [];
  }

  const index = tempTimeSchedule.value[day].indexOf(hour);
  if (index > -1) {
    tempTimeSchedule.value[day].splice(index, 1);
    if (tempTimeSchedule.value[day].length === 0) {
      delete tempTimeSchedule.value[day];
    }
  } else {
    tempTimeSchedule.value[day].push(hour);
    // 排序，方便展示
    tempTimeSchedule.value[day].sort((a, b) => a - b);
  }
};

// 确认时段选择
const confirmTimeSchedule = () => {
  formData.value.timeSchedule = { ...tempTimeSchedule.value };
  timeScheduleDialogVisible.value = false;
};

const showClearTimeSchedule = computed(() => {
  return Object.keys(formData.value.timeSchedule).filter(
    day => formData.value.timeSchedule[day].length > 0
  ).length;
});

// 获取已选择时段的文本描述
const getSelectedTimeScheduleText = () => {
  const days = Object.keys(formData.value.timeSchedule).filter(
    day => formData.value.timeSchedule[day].length > 0
  );
  if (days.length === 0) return "请选择投放时段";

  if (days.length === 7) {
    const allHours = days.every(day => {
      const hours = formData.value.timeSchedule[day];
      return hours && hours.length === 24;
    });

    if (allHours) return "全天投放";
  }

  return `已选择${days.length}天的部分时段`;
};

// 禁用开始日期（只能选择今天及以前的日期）
const disabledStartDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() > today.getTime();
};

// 禁用开始时间（如果是今天，则禁用今天之前的小时）
const disabledStartHours = () => {
  const today = new Date();
  const currentHour = today.getHours();
  return Array.from({ length: currentHour }, (_, i) => i);
};

// 禁用开始分钟（如果是当前小时，则禁用当前分钟之前的时间）
const disabledStartMinutes = (hour: number) => {
  const now = new Date();
  if (hour === now.getHours()) {
    return Array.from({ length: now.getMinutes() }, (_, i) => i);
  }
  return [];
};

// 禁用结束日期（不能早于开始日期）
const disabledEndDate = (time: Date) => {
  if (!formData.value.startTime) return false;
  const startDate = new Date(formData.value.startTime);
  startDate.setHours(0, 0, 0, 0);
  return time.getTime() < startDate.getTime();
};

const formatHour = (hour: number) => {
  const h = hour.toString().padStart(2, "0");
  return `${h}:00~${h}:59`;
};

// Add these near other ref declarations (around line 1180)
const pixelRefreshCooldown = ref(false);
const pixelRefreshCountdown = ref(0);

// Add this method near other refresh-related methods
const refreshKwaiPixelList = async () => {
  if (pixelRefreshCooldown.value) return;

  try {
    pixelRefreshCooldown.value = true;
    pixelRefreshCountdown.value = 60;

    // Start countdown
    const timer = setInterval(() => {
      pixelRefreshCountdown.value--;
      if (pixelRefreshCountdown.value <= 0) {
        clearInterval(timer);
        pixelRefreshCooldown.value = false;
      }
    }, 1000);

    // Refresh the Kwai Pixel list
    await loadKwaiPixelList();
  } catch (error) {
    console.error("刷新Kwai Pixel列表失败:", error);
    ElMessage.error("刷新失败");
  }
};
</script>

<style lang="scss" scoped>
.unit-form {
  width: 100%;
}

.form-group {
  margin-bottom: 28px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
}

.form-group-title {
  padding: 12px 16px;
  font-weight: 600;
  font-size: 16px;
  background-color: #f6f9fe;
  border-bottom: 1px solid #e5e7eb;
}

.form-group-content {
  padding: 16px;
}

.audience-selector {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selected-audience {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.audience-filter {
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding-top: 16px;
}

.schedule-selector {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.custom-schedule {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 8px;
  padding-left: 24px;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-label {
  min-width: 70px;
}

.time-schedule-selector {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.custom-time-schedule {
  margin-top: 8px;
}

.time-schedule-grid {
  max-height: 400px;
  overflow: auto;
}

.time-schedule-table {
  border-collapse: collapse;
  width: 100%;
}

.time-schedule-table th,
.time-schedule-table td {
  border: 1px solid #e5e7eb;
  text-align: center;
  padding: 8px 4px;
  font-size: 14px;
}

.time-schedule-table th {
  background-color: #f6f9fe;
  font-weight: 600;
}

.time-cell {
  width: 28px;
  height: 28px;
  cursor: pointer;
}

.time-cell:hover {
  background-color: #e6f7ff;
}

.time-cell.selected {
  background-color: #409eff;
}

.price-range-selector {
  display: flex;
  align-items: center;
  margin-top: 8px;
  gap: 8px;
}

.price-range-separator {
  margin: 0 4px;
}
</style>
